import os
import oss2
import hashlib
import time
from django.conf import settings
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile


class OSSClient:
    """阿里云OSS客户端"""
    
    def __init__(self):
        # OSS配置
        self.access_key_id = getattr(settings, 'OSS_ACCESS_KEY_ID', '')
        self.access_key_secret = getattr(settings, 'OSS_ACCESS_KEY_SECRET', '')
        self.endpoint = getattr(settings, 'OSS_ENDPOINT', 'https://oss-cn-hangzhou.aliyuncs.com')
        self.bucket_name = getattr(settings, 'OSS_BUCKET_NAME', 'huaxianguan')
        
        if self.access_key_id and self.access_key_secret:
            auth = oss2.Auth(self.access_key_id, self.access_key_secret)
            self.bucket = oss2.Bucket(auth, self.endpoint, self.bucket_name)
        else:
            self.bucket = None
    
    def upload_file(self, file_content, file_path, content_type=None):
        """
        上传文件到OSS
        
        Args:
            file_content: 文件内容（bytes或file对象）
            file_path: OSS中的文件路径
            content_type: 文件类型
        
        Returns:
            str: 文件的完整URL，失败返回None
        """
        if not self.bucket:
            return None
        
        try:
            # 上传文件
            headers = {}
            if content_type:
                headers['Content-Type'] = content_type
            
            result = self.bucket.put_object(file_path, file_content, headers=headers)
            
            if result.status == 200:
                # 返回完整的URL
                return f"https://{self.bucket_name}.{self.endpoint.replace('https://', '')}/{file_path}"
            else:
                return None
        except Exception as e:
            print(f"OSS上传失败: {e}")
            return None
    
    def upload_image_from_url(self, image_url, save_path):
        """
        从URL下载图片并上传到OSS
        
        Args:
            image_url: 图片URL
            save_path: OSS中的保存路径
        
        Returns:
            str: OSS中的完整URL，失败返回None
        """
        import requests
        
        try:
            # 下载图片
            headers = {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
            response = requests.get(image_url, headers=headers, timeout=10)
            response.raise_for_status()
            
            # 确定内容类型
            content_type = response.headers.get('content-type', 'image/jpeg')
            
            # 上传到OSS
            return self.upload_file(response.content, save_path, content_type)
        except Exception as e:
            print(f"从URL上传图片失败: {e}")
            return None
    
    def delete_file(self, file_path):
        """
        删除OSS中的文件
        
        Args:
            file_path: OSS中的文件路径
        
        Returns:
            bool: 删除是否成功
        """
        if not self.bucket:
            return False
        
        try:
            self.bucket.delete_object(file_path)
            return True
        except Exception as e:
            print(f"OSS删除失败: {e}")
            return False
    
    def generate_file_path(self, filename, folder='images'):
        """
        生成OSS文件路径
        
        Args:
            filename: 原始文件名
            folder: 文件夹名称
        
        Returns:
            str: 生成的文件路径
        """
        # 生成时间戳和哈希值避免重名
        timestamp = str(int(time.time()))
        hash_obj = hashlib.md5(f"{filename}{timestamp}".encode())
        hash_str = hash_obj.hexdigest()[:8]
        
        # 保留原始扩展名
        name, ext = os.path.splitext(filename)
        new_filename = f"{name}_{hash_str}{ext}"
        
        return f"{folder}/{new_filename}"


# 全局OSS客户端实例
oss_client = OSSClient()